package com.heima.search.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.common.exception.CustomException;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class ApUserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //将请求头中的用户信息存入到ThreadLocal中
        String userId = request.getHeader("userId");
        if (StringUtils.isBlank(userId)) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //存入
        ApUser apUser = new ApUser();
        apUser.setId(Integer.valueOf(userId));
        ApUserThreadLocalUtil.setUser(apUser);
        //放行
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理ThreadLocal
        ApUserThreadLocalUtil.clear();
    }
}
